<script setup>
import { useAuthStore } from '@/stores'
import { fetchUserAvatar, fetchUserRoleInfo, updateUserLoginInfo } from '@/service'
import { generateProxyPattern } from '@/config/proxy'
import { serviceConfig } from '@/../service.config'

const { url } = generateProxyPattern(serviceConfig[import.meta.env.MODE])
const { userInfo, token, logout, changIsRefreshAvatar } = useAuthStore()
const avatarUrl = ref('')
const createDate = ref('')
const role = ref('')
const roleInfo = ref('')
const formRef = ref()
const rPasswordFormItemRef = ref(null)
const formValue = ref({
  username: userInfo?.username,
  password: null,
  reenteredPassword: null
})
const accessToken = `Bearer ${token}`
const rules = {
  password: [
    {
      required: true,
      message: '请输入密码'
    }
  ],
  reenteredPassword: [
    {
      required: true,
      message: '请再次输入密码',
      trigger: ['input', 'blur']
    },
    {
      validator: validatePasswordStartWith,
      message: '两次密码输入不一致',
      trigger: 'input'
    },
    {
      validator: validatePasswordSame,
      message: '两次密码输入不一致',
      trigger: ['blur', 'password-input']
    }
  ]
}
function validatePasswordStartWith(_, value) {
  return !!formValue.value.password && formValue.value.password.startsWith(value) && formValue.value.password.length >= value.length
}
function validatePasswordSame(_, value) {
  return value === formValue.value.password
}
function handlePasswordInput() {
  if (formValue.value.reenteredPassword) {
    rPasswordFormItemRef.value?.validate({ trigger: 'password-input' })
  }
}
function handleValidateButtonClick(e) {
  e.preventDefault()
  formRef.value?.validate(async (errors) => {
    if (!errors) {
      const res = await updateUserLoginInfo(userInfo._id, {
        username: formValue.value.username,
        password: formValue.value.password
      })
      window.$message.success('修改用户信息成功, 请重新登录')
      logout()
    } else {
      window.$message.error(errors, '修改失败')
    }
  })
}
function getTimeOfDay() {
  const now = new Date()
  const hours = now.getHours()
  if (hours >= 0 && hours < 6) {
    return '凌晨' // 12:00 AM - 5:59 AM
  } else if (hours >= 6 && hours < 12) {
    return '早上' // 6:00 AM - 11:59 AM
  } else if (hours >= 12 && hours < 14) {
    return '中午' // 12:00 PM - 1:59 PM
  } else if (hours >= 14 && hours < 18) {
    return '下午' // 2:00 PM - 5:59 PM
  } else if (hours >= 18 && hours < 20) {
    return '傍晚' // 6:00 PM - 7:59 PM
  } else {
    return '晚上' // 8:00 PM - 11:59 PM
  }
}
async function beforeUpload(data) {
  if (data.file.file?.type !== 'image/png' && data.file.file?.type !== 'image/jpeg') {
    window.$message.error('只能上传png格式或jpeg格式的图片文件,请重新上传!')
    return false
  }
  if (data.file.file?.size > 2 * 1024 * 1024) {
    window.$message.error('图片大小不能超过 2MB,请重新上传!')
    return false
  }
  return true
}
async function updateFinish() {
  window.$message.success('头像修改成功')
  avatarUrl.value = await fetchUserAvatar(userInfo._id)
  changIsRefreshAvatar()
}
function areFieldsValid() {
  return formValue.value.username !== null && formValue.value.password !== null && formValue.value.reenteredPassword !== null && formValue.value.username.trim() !== '' && formValue.value.password.trim() !== '' && formValue.value.reenteredPassword.trim() !== ''
}
onMounted(async () => {
  createDate.value = new Date(userInfo.createTime).toLocaleDateString(undefined, { year: 'numeric', month: '2-digit', day: '2-digit' })
  if (!userInfo || !userInfo._id) return (avatarUrl.value = 'https://s2.loli.net/2024/08/12/YRsFoBrbfvOWDta.jpg')
  avatarUrl.value = await fetchUserAvatar(userInfo._id)
  const res = await fetchUserRoleInfo(userInfo.role_id)
  role.value = res.data.role_name
  roleInfo.value = res.data.role_desc
})
</script>

<template>
  <n-space vertical>
    <n-card title="个人信息">
      <n-flex>
        <n-grid :x-gap="300" :y-gap="8" :cols="2">
          <n-gi class="max-h-[210px]; min-w-[500px]">
            <n-card hoverable>
              <n-flex>
                <n-flex vertical>
                  <n-avatar round :size="128" :src="avatarUrl" />
                  <n-upload
                    :show-file-list="false"
                    method="PUT"
                    :action="`${url.value}/avatar/${userInfo._id}`"
                    :headers="{
                      authorization: accessToken
                    }"
                    @before-upload="beforeUpload"
                    @finish="updateFinish">
                    <n-button type="primary" secondary>
                      <template #icon>
                        <icon-park-outline-upload-picture />
                      </template>
                      修改头像
                    </n-button>
                  </n-upload>
                </n-flex>
                <n-descriptions label-placement="left" :column="1" :title="`${getTimeOfDay()}好，${userInfo?.username}，欢迎来到个人中心~`">
                  <n-descriptions-item label="id">
                    {{ userInfo?._id }}
                  </n-descriptions-item>
                  <n-descriptions-item label="用户名">
                    {{ userInfo?.username }}
                  </n-descriptions-item>
                  <n-descriptions-item label="注册时间">
                    {{ createDate }}
                  </n-descriptions-item>
                  <n-descriptions-item label="角色">
                    {{ role }}
                  </n-descriptions-item>
                </n-descriptions>
              </n-flex>
            </n-card>
          </n-gi>
          <n-gi>
            <n-flex>
              <n-card hoverable class="min-h-[210px]">
                <n-thing content-indented title="权限信息" :description="`生效于${createDate}`" :content="roleInfo">
                  <template #avatar>
                    <n-icon color="#de4307" size="24">
                      <icon-park-outline-chart-histogram />
                    </n-icon>
                  </template>
                  <template #header-extra>
                    <n-tag type="success">生效中</n-tag>
                  </template>
                </n-thing>
              </n-card>
            </n-flex>
          </n-gi>
        </n-grid>
      </n-flex>
    </n-card>
    <n-card title="密码修改">
      <n-space justify="center">
        <n-form ref="formRef" class="w-500px" :label-width="80" :model="formValue" :rules="rules">
          <n-form-item path="username" label="用户名">
            <n-input v-model:value="formValue.username" @keydown.enter.prevent placeholder="输入用户名" :disabled="true" />
          </n-form-item>
          <n-form-item path="password" label="密码">
            <n-input v-model:value="formValue.password" type="password" @input="handlePasswordInput" @keydown.enter.prevent placeholder="输入密码" />
          </n-form-item>
          <n-form-item ref="rPasswordFormItemRef" first path="reenteredPassword" label="重复密码">
            <n-input v-model:value="formValue.reenteredPassword" :disabled="!formValue.password" type="password" @keydown.enter.prevent placeholder="请再次输入密码" />
          </n-form-item>
          <n-form-item>
            <n-button :disabled="!areFieldsValid()" type="primary" attr-type="button" block @click="handleValidateButtonClick">修改</n-button>
          </n-form-item>
        </n-form>
      </n-space>
    </n-card>
  </n-space>
</template>
